package com.lsh.controller;

import com.lsh.exception.SysException;
import com.lsh.service.ArticleService;
import com.lsh.service.CommonService;
import com.lsh.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class IndexController {

    @Autowired
    IndexService indexService;

    @Autowired
    CommonService commonService;

    @Autowired
    ArticleService articleService;
    /**
     * 首页
     * @param mv
     * @return
     */
    @RequestMapping(value = "/index")
    public ModelAndView index(@CookieValue("TOKEN") String token, ModelAndView mv) throws SysException {
        String userId = indexService.findByUserId(token);
        if(userId == null) throw new SysException("token无效");
        else{
            Map<String, String> map = indexService.showUser(Integer.parseInt(userId));
            String nickName = map.get("nickName");
            String headPortrait = map.get("headPortrait");
            String province = map.get("province");
            String city = map.get("city");
            List articles = articleService.findArticleList();
            mv.addObject("nickname", nickName);
            mv.addObject("headPortrait", headPortrait);
            mv.addObject("pro", province);
            mv.addObject("cit", city);
            mv.addObject("articles", articles);
            mv.setViewName("/user/index");
        }
        return mv;
    }

    /**
     * 退出登录
     * @param mv
     * @return
     */
    @RequestMapping(value = "/logout")
    public ModelAndView logout(@CookieValue("TOKEN") String token , ModelAndView mv) throws SysException {
        indexService.logoutUser(token);
        mv.setViewName("redirect:/index");
        return mv;
    }

}
